package com.inossem.warehousemanage_tv;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.inossem.warehousemanage_tv.bean.BaseBean;
import com.inossem.warehousemanage_tv.bean.LoginBean;
import com.inossem.warehousemanage_tv.bean.PpBean;
import com.inossem.warehousemanage_tv.bean.WelBean_New;
import com.inossem.warehousemanage_tv.custom.MarqueeTextView;
import com.inossem.warehousemanage_tv.utils.Api;
import com.inossem.warehousemanage_tv.utils.LunarUtils;
import com.inossem.warehousemanage_tv.utils.MD5Utils;
import com.inossem.warehousemanage_tv.utils.OutsideClickDialog;
import com.inossem.warehousemanage_tv.utils.ToastUtils;
import com.inossem.warehousemanage_tv.utils.Utils;
import com.inossem.warehousemanage_tv.utils.requestUtils.InossemCallback;
import com.inossem.warehousemanage_tv.utils.requestUtils.RetrofitUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cn.bingoogolapple.bgabanner.BGABanner;
import retrofit2.Response;

/**
 * 欢迎页
 *
 * @author 詹建宇
 * @time on 2019/3/7 14:55
 * @email jianyu.zhan@inossem.com
 */
public class WelComeActivity_New extends FragmentActivity {
    private MarqueeTextView tvNotice;
    private TextView tvInventoryNum, tvInventoryMoney, tvInNum, tvInMoney, tvOutNum, tvOutMoney;
    private LinearLayout layoutDuty1, layoutDuty2;
    private TextView tvDuty1Name, tvDuty1Time, tvDuty2Name, tvDuty2Time;
    private TextView tvChineseYear;
    private BGABanner banner;
    private TextView tvMsg;
    private static final long SPEED = 1;//滚动速度
    private ImageView imgBg, imgRight, imgLeft;
    private TextView hour;
    /**
     * 时间监听有关
     */
    private IntentFilter intentFilter;
    private TimeChangeReceiver timeChangeReceiver;
    /**
     * 自动请求接口的时间间隔
     */
    private final static Integer PERIOD = 3;
    /**
     * 当前程序运行的是第几分钟
     */
    private Integer time = 0;
    private OutsideClickDialog dialog;
    private List<WelBean_New.DutyListBean> dutyList = new ArrayList<>();

    private int dutyPageTotal;
    private int pageIndex = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome_new);
        //阻止键盘压缩
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        initReceiver();
        initView();
        initData();
        if (mHandler.hasMessages(0)) mHandler.removeMessages(0);
        mHandler.sendEmptyMessageDelayed(0, 1000);
    }

    private void initView() {
        hour = findViewById(R.id.hour);
        tvNotice = findViewById(R.id.tv_notice);
        tvInventoryNum = findViewById(R.id.tv_inventory_num);
        tvInventoryMoney = findViewById(R.id.tv_inventory_money);
        tvInNum = findViewById(R.id.tv_in_num);
        tvInMoney = findViewById(R.id.tv_in_money);
        tvOutNum = findViewById(R.id.tv_out_num);
        tvOutMoney = findViewById(R.id.tv_out_money);
        layoutDuty1 = findViewById(R.id.layout_duty1);
        layoutDuty2 = findViewById(R.id.layout_duty2);
        tvDuty1Name = findViewById(R.id.tv_duty1_name);
        tvDuty1Time = findViewById(R.id.tv_duty1_time);
        tvDuty2Name = findViewById(R.id.tv_duty2_name);
        tvDuty2Time = findViewById(R.id.tv_duty2_time);
        tvChineseYear = findViewById(R.id.tv_chinese_year);
        banner = findViewById(R.id.banner);
        tvMsg = findViewById(R.id.tv_msg);
        imgBg = findViewById(R.id.img_bg);
        imgLeft = findViewById(R.id.imgLeft);
        imgRight = findViewById(R.id.imgRight);
        layoutDuty1.setVisibility(View.INVISIBLE);
        layoutDuty2.setVisibility(View.INVISIBLE);
        tvNotice.setSelected(true);
        tvMsg.setSelected(true);
        //左侧箭头
        imgLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageIndex--;
                initPage();
            }
        });

        //右侧箭头
        imgRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageIndex++;
                initPage();
            }
        });
    }

    private void initData() {
        RetrofitUtils.getRetrofit(this, "詹建宇", "岳凌云", "首页", "全部信息").create(Api.class).getWelInfo("2", "1", "1", "10", "2", String.valueOf(pageIndex)).enqueue(new InossemCallback<BaseBean<WelBean_New>>() {
            @Override
            public void success(Response<BaseBean<WelBean_New>> response) {
                WelBean_New bean = response.body().getBody();
                //通过初始化信息获取值班人总页数
                dutyPageTotal = Integer.parseInt(response.body().getBody().getDuty_page_total());
                setData(bean);
                checkButton(pageIndex,dutyPageTotal);
            }

            @Override
            public void failure(Response<BaseBean<WelBean_New>> response) {

            }
        });
    }

    //分页请求
    private void initPage() {
        RetrofitUtils.getRetrofit(this, "詹建宇", "岳凌云", "首页", "值班人").create(Api.class).getDutyList("2", String.valueOf(pageIndex), "2")//page_size是每页有几条数据，允许两行
                .enqueue(new InossemCallback<BaseBean<PpBean>>() {
                    @Override
                    public void success(Response<BaseBean<PpBean>> response) {
                        PpBean ppBean = response.body().getBody();
                        dutyList = ppBean.getDuty_list();
                        dutyPageTotal = Integer.parseInt(ppBean.getDuty_page_total());
                        setPage(dutyList);
                        checkButton(pageIndex,dutyPageTotal);
                    }

                    @Override
                    public void failure(Response<BaseBean<PpBean>> response) {

                    }
                });
    }

    private void setPage(List<WelBean_New.DutyListBean> list) {
        if (list == null || list.isEmpty() || list.size() != 2) {
            return;
        } else {
            for (int i = 0; i < 2; i++) {
                WelBean_New.DutyListBean dutyBean = list.get(i);
                if(i==0){
                    layoutDuty1.setVisibility(View.VISIBLE);
                    tvDuty1Name.setText(dutyBean.getUser_name());
                    tvDuty1Time.setText(dutyBean.getDuty_time().split(" ")[0]);
                }
                if(i==1){
                    layoutDuty2.setVisibility(View.VISIBLE);
                    tvDuty2Name.setText(dutyBean.getUser_name());
                    tvDuty2Time.setText(dutyBean.getDuty_time().split(" ")[0]);
                }
            }
        }
    }

    private void initReceiver() {
        intentFilter = new IntentFilter();
        //每分钟变化
        intentFilter.addAction(Intent.ACTION_TIME_TICK);
        timeChangeReceiver = new TimeChangeReceiver();
    }

    @SuppressLint("SetTextI18n")
    private void setData(WelBean_New bean) {

        //公告
        List<WelBean_New.NoticeListBean> noticeList = bean.getNotice_list();
        if (null != noticeList && !noticeList.isEmpty()) {
            tvNotice.setText(noticeList.get(0).getContent());
        }

        //数量金额
        tvInventoryNum.setText(bean.getTotal_inventory().getNumber());
        tvInventoryMoney.setText(bean.getTotal_inventory().getMoney() + bean.getTotal_inventory().getUnit());
        tvInNum.setText(bean.getIn_inventory().getNumber());
        tvInMoney.setText(bean.getIn_inventory().getMoney() + bean.getIn_inventory().getUnit());
        tvOutNum.setText(bean.getOut_inventory().getNumber());
        tvOutMoney.setText(bean.getOut_inventory().getMoney() + bean.getOut_inventory().getUnit());


        //值班人员
        dutyList = bean.getDuty_list();
        setPage(dutyList);

        //检测是否有值班人的左右箭头按钮
        checkButton(pageIndex,dutyPageTotal);

        //时间
        Calendar calendar = Calendar.getInstance();
        LunarUtils lunar = new LunarUtils(calendar);
        tvChineseYear.setText(lunar.toString());

        //轮播图
        List<WelBean_New.BannerListBean> bannerList = bean.getBanner_list();
        if (null != bannerList && !bannerList.isEmpty()) {
            imgBg.setVisibility(View.GONE);
            banner.setVisibility(View.VISIBLE);

            banner.setAdapter(new BGABanner.Adapter<ImageView, String>() {
                @Override
                public void fillBannerItem(BGABanner banner, ImageView itemView, @Nullable String model, int position) {
                    Glide.with(WelComeActivity_New.this).load(model).into(itemView);
                }
            });
            banner.setDelegate((banner, itemView, model, position) -> showDialog());
            List<String> urls = new ArrayList<>();
            for (WelBean_New.BannerListBean bannerBean : bannerList) {
                urls.add(Utils.showImg(bannerBean.getAddress()));
            }

            banner.setData(urls, null);
        } else {
            imgBg.setVisibility(View.VISIBLE);
            banner.setVisibility(View.GONE);
            imgBg.setOnClickListener(v -> showDialog());
        }

        //消息
        List<WelBean_New.NewsListBean> newsList = bean.getNews_list();
        if (null != newsList && !newsList.isEmpty()) {
            tvMsg.setText(newsList.get(0).getContent());
        }

    }
    private void showDialog() {
        dialog = new OutsideClickDialog(WelComeActivity_New.this, R.style.MyDialog) {
            @Override
            protected void onTouchOutside() {
                Window window = dialog.getWindow();
                assert window != null;
                EditText editText = window.findViewById(R.id.edit_pw);
                Utils.closeSoftKeyboard(editText);
            }
        };
        dialog.setContentView(R.layout.view_dialog_edit);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();

        Window window = dialog.getWindow();
        if (null == window) {
            return;
        }
        EditText editText = window.findViewById(R.id.edit_pw);
        TextView tvCancel = window.findViewById(R.id.tv_cancel);
        TextView tvSure = window.findViewById(R.id.tv_sure);
        tvCancel.setOnClickListener(v -> {
            Utils.closeSoftKeyboard(editText);
            dialog.dismiss();
        });
        tvSure.setOnClickListener(v -> {
            String pw = editText.getText().toString().trim();
            if (TextUtils.isEmpty(pw)) {
                ToastUtils.showToast("请输入密码");
            } else {
                login(dialog, editText);
            }
        });
    }

    private void login(Dialog dialog, EditText editText) {
        RetrofitUtils.getRetrofit(this, "詹建宇", "岳凌云", "首页", "登录").create(Api.class).login("2", MD5Utils.encrypt(editText.getText().toString().trim())).enqueue(new InossemCallback<BaseBean<LoginBean>>() {
            @Override
            public void success(Response<BaseBean<LoginBean>> response) {
                ToastUtils.showToast("登陆成功");
                Utils.closeSoftKeyboard(editText);
                dialog.dismiss();
                startActivity(new Intent(WelComeActivity_New.this, MainActivity.class));
            }

            @Override
            public void failure(Response<BaseBean<LoginBean>> response) {
                ToastUtils.showToast(response.body().getHead().getMsg());
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        time = 0;
        registerReceiver(timeChangeReceiver, intentFilter);
    }

    //hour
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    long time = System.currentTimeMillis();
                    Date date = new Date(time);
                    SimpleDateFormat format = new SimpleDateFormat("HH");
                    hour.setText(format.format(date));
                    break;
                default:
                    break;
            }
            sendEmptyMessageDelayed(0, SPEED);

        }

    };

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(timeChangeReceiver);
    }

    class TimeChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (null == intent.getAction()) {
                return;
            }
            String s = intent.getAction();
            if (s.equals(Intent.ACTION_TIME_TICK)) {

                if (null == time || null == PERIOD || 0 == PERIOD) {
                    return;
                }
                time++;
                if (time % PERIOD == PERIOD - 1) {
                    initView();
                    initData();
                }
            }
        }
    }

    private void checkButton(int index, int total) {
        if (index == 1) {
            //第一页
            imgLeft.setVisibility(View.INVISIBLE);
            if(index==total){
                //只有一页
                imgRight.setVisibility(View.INVISIBLE);
            }else{
                //存在多页
                imgRight.setVisibility(View.VISIBLE);
            }
        } else {
            if (index == total) {
                //最后一页
                imgLeft.setVisibility(View.VISIBLE);
                imgRight.setVisibility(View.INVISIBLE);
            } else {
                //中间页
                imgLeft.setVisibility(View.VISIBLE);
                imgRight.setVisibility(View.VISIBLE);
            }
        }
    }
}